package com.mtzqc.common.app

import android.app.ActivityManager
import android.content.Context
import com.blankj.utilcode.util.Utils
import com.didi.drouter.api.DRouter
import com.mtzqc.SupportApp
import com.mtzqc.common.init.StartHelper
import com.tencent.mmkv.MMKV
import com.tencent.mmkv.MMKVLogLevel
import java.util.*

abstract class BaseApplication : SupportApp() {
    override fun onCreate() {
        super.onCreate()
        if (isMainProcess()) {
            beforeInitLib()
            initLib()
            afterInitLib()
        }
    }


    open fun isMainProcess(): Boolean {
        try {
            var pid = android.os.Process.myPid()
            var pck = applicationInfo.packageName
            val activityManager: ActivityManager =
                getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            return null != activityManager.runningAppProcesses.firstOrNull {
                return it.pid == pid && Objects.equals(pck, it.processName)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    open fun beforeInitLib() {

    }

    open fun afterInitLib() {

    }

    open fun initLib() {
        initLibImpl(App.isDebug(), App.isDev())
    }


    open fun initLibImpl(debug: Boolean, dev: Boolean) {
        initMMKV(debug, dev)
        initDRouter(debug, dev)
        initUtils(debug, dev)
        initOtherLib(debug, dev)
    }

    open fun initUtils(debug: Boolean, dev: Boolean) {
        Utils.init(this)
    }


    open fun initMMKV(debug: Boolean, dev: Boolean) {
        MMKV.initialize(
            this,
            if (App.isDebug()) MMKVLogLevel.LevelDebug else MMKVLogLevel.LevelWarning
        )
    }

    open fun initDRouter(debug: Boolean, dev: Boolean) {
        DRouter.init(this)
    }


    /*   open fun initSmartRefreshLayout(debug: Boolean, dev: Boolean) {
           SmartRefreshLayout.setDefaultRefreshHeaderCreator { ctx: Context?, layout: RefreshLayout ->
               layout.setEnableLoadMore(false)
               ClassicsHeader(ctx)
           }
       }*/


    open fun initOtherLib(debug: Boolean, dev: Boolean) {
        StartHelper.initServices()
    }
}